package com.huffman.smart_picture.manager;

import cn.hutool.core.io.FileUtil;
import com.huffman.smart_picture.common.exception.BusinessException;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.utils.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author DengLin
 * @date 2025/1/18 14:49
 * @description: 图片文件上传
 */
@Service
@Slf4j
public class FilePictureUpload extends PictureUploadTemplate{
    @Override
    protected void validPicture(Object inputSource,boolean ignoreSize) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtil.throwIf(multipartFile == null, ErrorEnum.UPLOAD_FILE_EMPTY, "文件不能为空");
        // 校验文件大小
        long size = multipartFile.getSize();
        ThrowUtil.throwIf(size > 3 * ONE_M, ErrorEnum.UPLOAD_FILE_OVERSIZE, "文件大小超过3MB");
        //校验文件类型
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtil.throwIf(!ALLOW_FILE_TYPE.contains(suffix), ErrorEnum.FILE_TYPE_ERROR, "文件类型错误");
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            log.error("picture upload failed:{}",e.getStackTrace());
            throw new BusinessException(ErrorEnum.SYSTEM_ERROR,"图片上传失败");
        }
    }
}
